package com.yang.String_;

public class LeetCode541 {
    public static void main(String[] args) {
        String s = "abcd";
        SolutionLeetCode541 solutionLeetCode541 = new SolutionLeetCode541();
        String a = solutionLeetCode541.reverseStr(s,2);
        System.out.println(a);
    }
}
class SolutionLeetCode541 {
    public String reverseStr(String s, int k) {
        char[] chars = s.toCharArray();
        for (int i = 0; i < s.length(); i += 2*k) {
            int start = i;
            int end;
            // 如果剩余字符串长度小于k就让end直接到结尾(这样就是k反转)
            if(k+i >= s.length()){
                 end = s.length() - 1;
            }
            // 否则就是2K反转
            else {
                end = start+k-1;
            }
            while (end > start){
                chars[start] ^= chars[end];
                chars[end] ^= chars[start];
                chars[start] ^= chars[end];
                end--;
                start++;
            }
        }
     return new String(chars);
    }
}
